import Axios, { Method, ResponseType, AxiosResponse, AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
// import { useRouter } from 'vue-router'
import EnvermentConfig from '../../../public/config'
import Vrouter from "@/router"



interface IAxiosData {
  url: string
  method: Method
  headers?: any
  json: boolean
  contentType?: string
  data?: any
  params?: any
  timeout?: number
  responseType?: ResponseType
}

// const router = useRouter()

const timeout = 2000;
const baseURL = EnvermentConfig.baseUrl;
const auth = {
  username: EnvermentConfig.authClientId,
  password: EnvermentConfig.authSecret
}
const axios = Axios.create({
  baseURL,
  timeout,
  // auth
})

// 允许携带cookie
axios.defaults.withCredentials = true
// 请求头信息
// axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
// 默认使用 application/json 形式
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*'
axios.defaults.withCredentials = true

// 添加请求拦截器，在请求发出之前添加 Authorization 头
axios.interceptors.request.use((config: AxiosRequestConfig) => {
  const token = sessionStorage.getItem('accessToken')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  } else {
    config.auth = auth;
  }
  return config;
}, error => Promise.reject(error));

// 响应拦截器
axios.interceptors.response.use(
  (res: AxiosResponse) => res,
  (err) => {
    if (err.response && err.response.data) {
      const code = err.response.status
      const msg = err.response.data.msg
      ElMessage.error(`${code}, ${msg}`)
      if (code === 401) { // 未认证
        sessionStorage.clear();
        Vrouter.push('/login');
      }
    } else {
      ElMessage.error(`${err}`)
    }
    return Promise.reject(err)
  }
)

/** *
 * axios({url,method,content,params,datas})
 *
 * @param {string}  url，(必填)
 * @param {string}  method,默认post
 * @param {boolean} json, content-type类型，(必填)
 * @param {object}  params
 * @param {object}  datas  //token在datas中
 * 
 * 响应数据格式
 *  {"code":401,"success":false,"desc":"无效的请求","msg":"未授权部门","respData":null}
 *
 */
export default function request(reqApi: IAxiosData) {
  return new Promise<any>((resolve, reject) => {
    // arr = requestValidate(arr)
    axios({
      timeout: reqApi.timeout === undefined ? 10000 : reqApi.timeout, // 请求超时时间
      url: reqApi.url,
      method: reqApi.method || 'POST',
      headers: {
        'content-type': reqApi.contentType ? reqApi.contentType : reqApi.json ? 'application/json; charset=UTF-8' : 'application/x-www-form-urlencoded; charset=UTF-8'
      },
      params: reqApi.params || '',
      data: reqApi.data || '',
      responseType: reqApi.responseType || 'json'
    })
      .then((response: AxiosResponse<any>) => {
        // const responseStatus = `${response.status}`
        const responseStatus = response.status
        // 状态码2开头的处理逻辑
        if (responseStatus === 200) {
          resolve(response.data)
        } else if (responseStatus === 401) { // 未认证
          ElMessage({
            type: 'warning',
            message: response.data.msg
          })
          reject(response.data)
          sessionStorage.clear;
          Vrouter.push('/login');
        } else {
          ElMessage({
            type: 'warning',
            message: response.data.msg
          })
          reject(response.data)
        }
      })
      .catch((err) => {
        // ElMessage({
        //   type: 'error',
        //   message: err.message
        // })
        reject(err)
      })
  })
}
